import datetime
import os

from flask import Blueprint, abort, render_template, session, request, url_for, current_app

from utils.generate_thumbnail import parse_image_url, generate_thumbnail
from app.models.tablemodel import Article, Credit, Users, Favorite, Comment
from utils.redis_util import redis_client

ar_bp = Blueprint('article', __name__)


@ar_bp.route('/article/<int:articleid>')
def read(articleid):
    try:
        # 返回数据格式（Article,'niackname'）
        result = Article().find_by_id(articleid)
        if result is None:
            abort(404)
    except Exception as e:
        abort(500)
    dic = {}
    for k, v in result[0].__dict__.items():
        if not k.startswith('_sa_instance_state'):
            dic[k] = v
    dic['nickname'] = result.nickname
    # 阅读次数加，用redis来做，减少数据库访问
    # 增加阅读计数 - 使用哈希存储每篇文章的阅读量
    # 基于IP和文章ID生成唯一标识，防止同一IP重复计数
    # ip = request.remote_addr
    # key = f"post:{articleid}:viewed:{ip}"
    # # 检查此IP是否在24小时内已访问过
    # if not redis_client.exists(key):
    #     # 增加阅读计数
    #     redis_client.hincrby('post:views', articleid, 1)  # 增加阅读计数 - 使用哈希存储每篇文章的阅读量，用于最终持久化加到数据库中
    #     redis_client.zincrby('post:views:rank', 1, articleid)  # 同时使用有序集合维护阅读排行榜
    #
    #     # 设置24小时过期
    #     redis_client.setex(key, 86400, 1)

    Article().update_read_count(articleid)  # 阅读次数加1
    position = -1
    paid_flag = Credit().check_paid_article(articleid)
    if dic['credit'] > 0 and dic['nickname'] != session['nickname'] and (not paid_flag):
        # 检查是否为文章付过费，没有付过费，则截断文章，并且通过判断paid_flag=False来显示付费按钮
        content = dic['content']
        position = int(len(content) / 2)
        temp = content[0:int(len(content) / 2)]
        if temp.rfind('</p>') > 0:
            position = temp.rindex('</p>') + 4  # 找到紧挨着的</p>标签
            dic['content'] = temp[0:position]
        else:
            dic['content'] = temp
    is_favorited = Favorite().check_favorite(articleid)  # 是否收藏
    pre_next_dict = Article().find_prev_next_by_id(articleid)  # 上一篇下一篇推荐
    comment_user = Comment().find_limit_with_user(articleid, 0, 50)
    return render_template('article.html', article=dic, position=position, paid_flag=paid_flag,
                           is_favorited=is_favorited, pre_next_dict=pre_next_dict, comment_user=comment_user)


# 需要积分的文章查看全部内容的路由接口
@ar_bp.route('/readall', methods=['POST'])
def read_all():
    articleid = request.form.get("articleid")
    position = int(request.form.get('position'))
    result = Article().find_by_id(articleid)
    content = result[0].content[position:].strip()
    paid_flag = Credit().check_paid_article(articleid)
    if not paid_flag:
        if Users().find_by_username(session.get('username'))[0].credit < result[0].credit:
            # 用户积分不足，看不了文章
            return 'not_enough_credit'
        else:
            # 添加积分明细
            Credit().insert_detail('阅读文章', target=articleid, credit=-1 * result[0].credit)
            # 减少用户表剩余积分
            Users().update_credit(credit=-1 * result[0].credit)
    return content


# 展示文章编辑页面
@ar_bp.route('/post/create', methods=['GET'])
def new_post():
    return render_template('post_create.html')


# 向数据库插入新增文章的接口
@ar_bp.route('/posts', methods=['POST'])
def create_post():
    data = request.get_json()
    content = data.get('content')
    type = int(data.get('type'))
    accessible = int(data.get('accessible'))
    credit = int(data.get('credit'))
    drafted = int(data.get('drafted'))
    # checked = data.get('checked') #目前可以让大家都发文章
    headline = data.get('headline')
    articleid = int(data.get('articleid'))
    if session.get('userid') is None:
        return "perm-denied"
    else:
        url_list = parse_image_url(content)
        if len(url_list) > 0:
            thumbnail = generate_thumbnail(url_list)
        else:
            thumbnail = ''  # 文章没有图片就没有缩略图
        # 再判断articleid是否为0，如果为0则表示是新数据
        if articleid == 0:
            try:
                art_id = Article().insert_article(headline=headline, content=content, thumbnail=thumbnail, type=type,
                                                  accessible=accessible,
                                                  credit=credit,
                                                  drafted=drafted, checked=1)
                # 配合静态化处理，删除旧的静态化页面
                for file in os.listdir(os.path.join(current_app.root_path, 'templates', 'index_static')):
                    os.remove(os.path.join(current_app.root_path, 'templates', 'index_static', file))

                return str(art_id)
            except Exception as e:
                print(e)
                return 'post-fail'
        else:
            # 如果是已经添加过的文章，则做修改操作
            try:
                art_id = Article().update_article(articleid=articleid, headline=headline, content=content,
                                                  thumbnail=thumbnail,
                                                  type=type,
                                                  accessible=accessible,
                                                  credit=credit,
                                                  drafted=drafted, checked=1)
                return str(art_id)
            except Exception as e:
                return 'post-fail'
